var page = 0;
function category_slider_init(type) {            
    $("#" + type + " .category-slider").scrollable({ vertical: true, mousewheel: true });    
}
function product_slider_init(category) {			
	$("#" + category + " .product-slider").scrollable({ vertical: true, mousewheel: true });
	var capi = $("#" + category + " .product-slider").data("scrollable");
	if(capi){
		scroll_handler(capi, 0, "list");
	    capi.onSeek(function() {
	    	scroll_handler(this, this.getIndex(), "list");
	    });
	}
}
function product_image_slider_init(products) {
	var index = $("#" + products + " .product-image-slider .items").attr('index');
    $("#" + products + " .product-image-slider").scrollable({ initialIndex: index, mousewheel: true });
    var papi = $("#" + products + " .product-image-slider").data("scrollable");
    if(papi){
    	scroll_handler(papi, index, "view");
	    papi.onSeek(function() {
	    	scroll_handler(this, this.getIndex(), "view");
	    });
    }
}

function scroll_handler(api, index, slider){
	var items = api.getItems();
	var $item = $(items[index]);
	// fav button change follow image scroll
	var $img = $item.find("img.fav");
	if (slider == "view"){
		var $a = $("#viewFavButton");
		if ($a.length != 0){
			$a.attr("ref", $img.attr("ref"));
			var link = "";
			if ($img.attr("ref") == "remove"){
				$a.find('img').attr("src", ctx+"/images/icons/heart-liked.png");
				link = ctx+"/user/removeFavProduct/?uid="+ $img.attr("uid") +"&pid="+ $img.attr("pid");
				$a.attr("href", link);
			}
			else if ($img.attr("ref") == "add"){
				$a.find('img').attr("src", ctx+"/images/icons/heart-normal.png");
				link = ctx+"/user/addFavProduct/?uid="+ $img.attr("uid") +"&pid="+ $img.attr("pid");
				$a.attr("href", link);
			}
			//auto slide the parent list of products view
			p = $a.attr("parentId");
			if(p){
				pi = (Math.floor(index/9));
				var papi = $("#" + p + " .product-slider").data("scrollable");
				if(pi != page){
					page = pi;
					capi.seekTo(pi,0);
				}
			}
		}
	}
	
	//lazy load image and the image of next page
	$item.find("img.empty").each(function(){
		$(this).attr("src", $(this).attr("hsrc"));
		$(this).removeClass("empty");
	});
	var $nextItem = $(items[index+1]);
	if($nextItem.children().length!=0)
	{
		$nextItem.find("img.empty").each(function(){
			$(this).attr("src", $(this).attr("hsrc"));
			$(this).removeClass("empty");
		});
	}
}

function productListSearch(view){
    var a= "/searchList/productSearchByNameList/?view="+view+"&keyword=";
    $("#buttonName").attr('disabled', 'disabled');
    $("#buttonBrand").attr('disabled', '');
    $("#buttonStore").attr('disabled', '');
    $("#hiddenProduct").val(a);
    $("#searchKeyWord").attr("placeholder","Tìm kiếm theo tên sản phẩm");
    //var arrayName = $('#hiddenName').val();
    //data = arrayName.split(',');
    //AutoComplete_Create('searchKeyWord', data);  
}
function storeListSearch(view){
    var a= "/searchList/productSearchByStoreList/?view="+view+"&keyword=";
    $("#buttonName").attr('disabled', '');
    $("#buttonBrand").attr('disabled', '');
    $("#buttonStore").attr('disabled', 'disabled');
    $("#hiddenProduct").val(a);
    $("#searchKeyWord").attr("placeholder","Tìm kiếm theo tên cửa hàng");
    //var arraySearch = $('#hiddenStore').val();
    //data = arraySearch.split(','); 
    //AutoComplete_Create('searchKeyWord', data);    
}
function brandListSearch(view){    
    var a= "/searchList/productSearchByBrandList/?view="+view+"&keyword=";
    $("#buttonName").attr('disabled', '');
    $("#buttonBrand").attr('disabled', 'disabled');
    $("#buttonStore").attr('disabled', '');
    $("#hiddenProduct").val(a);
    $("#searchKeyWord").attr("placeholder","Tìm kiếm theo tên thương hiệu");
    //var arrayBrand = $('#hiddenBrand').val();
    //data = arrayBrand.split(',');
    //AutoComplete_Create('searchKeyWord', data);    
}

function loadUrl(){
	var keyword = $('#searchKeyWord').val();
    var url = ctx +  $("#hiddenProduct").val() + keyword + "&back=Back";
    if(keyword == ""){
    	$('#search_link').attr('href', '#');
    	$("#searchKeyWord").attr("placeholder","Nhập từ khóa cần tìm");
    }
    else
    	$('#search_link').attr('href', url);
}

function checkEmail(email) {
	var str = "^([a-zA-Z0-9_-]+[\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9_-]+[\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$";
	var re = new RegExp(str);
	if (re.test(email)) {
		return true;
	}
	return false;
}

function isNumeric(elem){
	var numericExpression = /^[0-9]+$/;
	if(elem.val().match(numericExpression)){
		return true;
	}else{
		return false;
	}
}

function validateLoginForm(){
	var flag = true;
	if($("#username").val().length < 4){
		$("#username").val("");
		$("#username").attr('placeholder','Username không đúng');
		flag = false;
	}
	if($("#password").val() == ""){
		$("#password").attr('placeholder','Password không được bỏ trống');
		flag = false;
	}
	return flag;
}

function logMeIn(){
	$("#logMeIn").ajaxSubmit({
		beforeSubmit: validateLoginForm,
		success: function(data){
			if(data == 'true'){
				location.reload();
			}
			else{
				alert("Username và password không đúng");
			}
		}
		//error: alert("Kết nối không thành công")
	}, "text");
}

function validateForm(){
	var flag = true;
	if($("#rusername").val().length < 4){
		$("#rusername").val("");
		$("#rusername").attr('placeholder','Username không được ít hơn 4 ký tự');
		flag = false;
	}
	if($("#rpassword").val() == ""){
		$("#rpassword").attr('placeholder','Password không được bỏ trống');
		flag = false;
	}
	if(!isNumeric($("#phone"))){
		$("#phone").val("");
		$("#phone").attr('placeholder','Phone chỉ chứa số');
		flag = false;
	}
	if(isNumeric($("#phone")) && $("#phone").val().length < 8){
		$("#phone").val("");
		$("#phone").attr('placeholder','Phone có ít nhất 8 số');
		flag = false;
	}

	if($("#rpassword").val() != $("#repassword").val()){
		$("#repassword").val('');
		$("#repassword").attr('placeholder','Password nhập lại không giống');
		flag = false;
	}
	if(!checkEmail($("#email").val())){
		$("#email").val('');
		$("#email").attr('placeholder','Địa chỉ email không hợp lệ');
	}
	return flag;
}

function registerMeIn(){
	$("#registerMeIn").ajaxSubmit({
		beforeSubmit: validateForm,
		success: function(data) {
			if(data == "0")
				alert("Username đã tồn tại.");
			if(data == "1")
				alert("Email đã tồn tại.");
			if(data == '2'){
				location.reload();
			}
		}        
    }, "text");
}

function checkLoadedList(a){
	$list = $("#list-" + $(a).attr("cid"));
	if ($list.length){
		$(a).attr("href", "#list-" + $(a).attr("cid"));
		var ci = $(a).attr("index");
		var capi = $("#list-" + $(a).attr("cid") + " .product-image-slider").data("scrollable");
		capi.seekTo(ci,0);
		console.log(ci);
		//capi.seekTo(ci,0,function(){});
//		$items = $list.find("div.items");
//		if($items){
//			var po = ci*320;
//			$items.attr("style","left: -" + po + "px;");
//		}
	}
}

function changeFavButton(a, ref){
	if (ref == "add"){
		var oldAddr = a.attr('href');
		var newAddr = oldAddr.replace('addFavProduct','removeFavProduct');
		a.attr('href', newAddr);
		var oldImg = a.find('img').attr("src");
		var newImg = oldImg.replace("heart-normal","heart-liked");
		a.find('img').attr("src", newImg);
		a.attr('ref', 'remove');
	}
	else if (ref == "remove"){
		var oldAddr = a.attr('href');
		var newAddr = oldAddr.replace('removeFavProduct','addFavProduct');
		a.attr('href', newAddr);
		var oldImg = a.find('img').attr("src");
		var newImg = oldImg.replace("heart-liked","heart-normal");
		a.find('img').attr("src", newImg);
		a.attr('ref', 'add');
	}
}

function processViewFavProduct(a){
	$.get($(a).attr('href'), function(data) {
		if(data == "true"){
			changeFavButton($(a), $(a).attr('ref'));
			
			var api = $(a).parent().parent().find("div.product-image-slider").data("scrollable")
			var index = api.getIndex();
			var items = api.getItems();
			var $item = $(items[index]);
			var $img = $item.find("img.fav");
			$img.attr("ref", $(a).attr('ref'));
		
			var $detailView = $("#proview"+$img.attr("pid"));
			var set = $detailView.lenght;
			if ($detailView.length != 0){
				var $da = $detailView.find("div.toolbar").find("#detailFavButton");
				if ($da){
					changeFavButton($da, $da.attr('ref'));
				}
			}
		}
	});
	return false;
}

function processFavProduct(a){
	$.get($(a).attr('href'), function(data) {
		if(data == "true"){
			changeFavButton($(a), $(a).attr('ref'));		
			var $pageView = $("#"+$(a).attr("parentid"));
			if ($pageView.length != 0){
				var $da = $pageView.find("div.toolbar").find("#viewFavButton");
				if ($da){
					changeFavButton($da, $da.attr('ref'));
				}
			}
		}
	});
	return false;
}